package com.astersoft.lib.generator;

/*
 * Copyright 2012 AsterSoft personal developer - Licensed under the Apache
 * License, Version 2.0 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
 * or agreed to in writing, software distributed under the License is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */

import com.astersoft.lib.generator.algorithm.MersenneTwisterFast;

/**
 * Generate random string
 * 
 * @author dario durzo
 * @version 0.1
 * @date 26-08-2009
 */
public class ASRandomString {
	private static MersenneTwisterFast mtf = null;

	/**
	 * Generate random string
	 * 
	 * @param lo - minor size
	 * @param hi - major size
	 * @return - the random String with lo < size < hi
	 */
	public static String generate(int lo, int hi){
		int n = rand(lo, hi);
		byte b[] = new byte[n];
		for (int i = 0; i < n; i++)
			b[i] = (byte)secureRand('a', 'z');
		
		return new String(b);//, Charset.defaultCharset());
	}
	
	private static int secureRand(int lo, int hi) {
		if(mtf == null) mtf = new MersenneTwisterFast();
		int scarto = mtf.nextInt(hi - lo);
		
		return lo + scarto;
	}

	private static int rand(int lo, int hi){
		java.util.Random rn = new java.util.Random();
		int n = hi - lo + 1;
		int i = rn.nextInt() % n;
		if (i < 0)
			i = -i;
		return lo + i;
	}

	/**
	 * Default random string generation
	 * 
	 * @return - random string with length between 5 and 9 chars
	 */
	public static String generate(){
		return generate(5, 9);
	}
	
	public static void main(String[] args){
		System.out.println(ASRandomString.generate(5, 10));
	}
}